package com.ticket.sass.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.sass.admin.mapper.AppCinemaMapMapper;
import com.ticket.sass.admin.service.BaseService;
import com.ticket.sass.common.entity.tenant.AppCinemaMapEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-04-07
 */
@Service
public class AppCinemaMapServiceImpl extends ServiceImpl<AppCinemaMapMapper, AppCinemaMapEntity> implements BaseService<AppCinemaMapEntity> {
    public Map<Long, Boolean> getEnabledStatusForAppIds(List<Long> appIds, Long cinemaId) {
        // 如果传入的列表为空，则直接返回空的结果Map
        if (appIds == null || appIds.isEmpty()) {
            return new HashMap<>();
        }
        
        // 构造查询条件，查询对应的记录
        QueryWrapper<AppCinemaMapEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("app_id", appIds);
        queryWrapper.eq("cinema_id", cinemaId);
        List<AppCinemaMapEntity> entities = this.list(queryWrapper);
        
        // 将查询结果转换为Map
        return entities.stream()
            .collect(Collectors.toMap(AppCinemaMapEntity::getAppId, AppCinemaMapEntity::getEnable));
    }
    
    
    public void updateOrCreateRecord(Long cinemaId, Long appId, Boolean enabled) {
        // 查询是否存在记录
        QueryWrapper<AppCinemaMapEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cinema_id", cinemaId).eq("app_id", appId);
        AppCinemaMapEntity existingRecord = this.getOne(queryWrapper);
        
        // 如果存在记录
        if (existingRecord != null) {
            // 如果enable字段与传入的值不同，则更新
            if (!existingRecord.getEnable().equals(enabled)) {
                existingRecord.setEnable(enabled);
                this.updateById(existingRecord);
            }
        } else {
            // 如果不存在记录，则创建新记录
            AppCinemaMapEntity newRecord = new AppCinemaMapEntity();
            newRecord.setCinemaId(cinemaId);
            newRecord.setAppId(appId);
            newRecord.setEnable(enabled);
            this.save(newRecord);
        }
    }
    
    public Boolean getEnabledStatusForAppIds(Long appId) {

        // 构造查询条件，查询对应的记录
        QueryWrapper<AppCinemaMapEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_id", appId);
        AppCinemaMapEntity one = this.getOne(queryWrapper);
        return !Objects.isNull(one) && one.getEnable();
    }
}
